package com.iqiyi.pps.epg.web.timer;

import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.core.model.record.RecordTaskRule;
import com.iqiyi.pps.epg.core.model.task.SimpleTaskType;
import com.iqiyi.pps.epg.core.service.record.IRecordAsyncService;
import com.iqiyi.pps.epg.core.service.record.IRecordService;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by karkarrotxu on 2018/4/20.
 */
public class RecordTaskAppendTrigger {
    private static Logger logger = LoggerFactory.getLogger(RecordTaskAppendTrigger.class);
    @Autowired
    private IRecordAsyncService recordAsyncService;
    @Autowired
    private IRecordService recordService;

    public void task() {
        logger.info("[RecordTaskAppendTrigger] start trigger");
        long startTime = System.currentTimeMillis();
        //, int dayAfter
        int createDay = Configuration.getInt("record.task.createDay");
        //int dayAfter = createDay + 1;
        long checkEndTime = DateTimeUtil.getDayEndTime(startTime + DateTimeUtil.DAY_TIME * (createDay - 1));
        List<Criterion> cList = new ArrayList<Criterion>();
        cList.add(Restrictions.isNotNull("nextExecuteTime"));
        cList.add(Restrictions.geProperty("stopTime", "nextExecuteTime"));
        cList.add(Restrictions.eq("status", 1));
        cList.add(Restrictions.le("nextExecuteTime", new Timestamp(checkEndTime)));
        List<RecordTaskRule> resultList = recordService.queryTaskRuleByCriterion(cList, null);
        for (RecordTaskRule temp : resultList) {
            recordAsyncService.addRecordRuleAppendTask(temp.getPlanId(), temp.getStopTime().getTime() < checkEndTime ? temp.getStopTime().getTime() : checkEndTime);
        }
        recordAsyncService.triggerAppendOnce();
        logger.info("[RecordTaskAppendTrigger] end trigger time:" + (System.currentTimeMillis() - startTime));
    }
}
